﻿using AppUpdates.Core;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using SystemUpdatesCore.Server.Network;
using SystemUpdatesCore;
using SystemUpdatesCore.Server;
using SystemUpdatesCore.Client;

namespace AppUpdates
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            this.Loaded += async (s, e) =>
            {

                bar1.Maximum = 100;

                //绑定事件
                appUpdate.server.DownloadProgressChanged += ServerFiles_DownloadProgressChanged;
                appUpdate.server.DownloadFileCompleted += ServerFiles_DownloadFileCompleted;

                lblTitle.Content = $"{systemName}更新";
            };

            appUpdate.server.Urls = new List<ServerUrlModel>() {
                  new ServerUrlModel(1, "https://gitee.com/ypeuee/auto-key-mouse-update/raw/master/version.txt" ),
           };
            appUpdate.server.Url = appUpdate.server.Urls[0];
        }

        AppUpdate appUpdate = new AppUpdate();

        string appPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "鼠标点点器.exe");
        string systemName = "鼠标点点器";

        /// <summary>
        /// 更新进度
        /// </summary>
        /// <param name="value"></param>
        void UpdBarValue(int value)
        {
            if (bar1.Dispatcher.Thread != System.Threading.Thread.CurrentThread)
                bar1.Dispatcher.Invoke(() => bar1.Value = value);
            else
                bar1.Value = value;
        }

        /// <summary>
        /// 显示信息
        /// </summary>
        /// <param name="message"></param>
        void Msg(string message)
        {
            if (lblMsg.Dispatcher.Thread != System.Threading.Thread.CurrentThread)
                lblMsg.Dispatcher.Invoke(() => lblMsg.Content = message);
            else
                lblMsg.Content = message;
        }

        /// <summary>
        /// download 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        async void Update()
        {

            var clientModel = new SystemUpdatesCore.Client.ClientUrlMode(ClientVersionEnum.File, Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "version.txt"));

            //var isNew = appUpdate.IsNew(clientModel, systemName);



            var ver = await appUpdate.server.GetVersion(systemName);
            if (ver == null)
            {
                Msg("下载失败，未获取到服务端版本");
                return;
            }
            //var loadVer = appUpdate.client.GetVersion(clientModel);
            //if (loadVer.Result?.Version == ver.Version)
            //{
            //    Msg("已经是新版本。");
            //    return;
            //}

            Msg("下载中...");

            await appUpdate.server.DownloadFilesTaskAsync(ver);

            Msg("解压中...");
            var dirs = await Zip.ExtractToDirectoryTaskAsync(ver.UpdateFiles.Select(m => m.FileName).ToList());


            Msg("安装中...");
            var docPath = AppDomain.CurrentDomain.BaseDirectory;
            foreach (string dir in dirs)
            {
                FileCopy.Copy(dir, docPath);

                //清理
                Directory.Delete(dir, true);
                File.Delete(dir + ".zip");

            }

            RunApp.Run(appPath, false);

            //退出程序  
            System.Environment.Exit(0);
        }

        /// <summary>
        /// 全部下载完成
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ServerFiles_DownloadFileCompleted(object? sender, NetworkAsyncCompletedEventArgs e)
        {
            Msg(e.Error != null ? $"下载失败{e.Error}" : $"下载完成{e.DownloadNum} / {e.TotalDownloadNum}");

        }


        /// <summary>
        /// 下载进度
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ServerFiles_DownloadProgressChanged(object sender, NetworkDownloadProgressChangedEventArgs e)
        {
            UpdBarValue(e.ProgressPercentage);
        }


        private void btnUpdate_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Update();
            }
            catch (Exception ex)
            {
                Msg($"更新失败：{ex.Message}");
            }
        }

        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {
            Close();
        }
    }
}
